#!/bin/sh
#
# This script will download 10Gb+ from AOSP git repositories, make sure
# you know what you do before running it. If you do, you probably will
# want to save produced mirror for later use ;-). Mirror create is fully
# compatible with what would be produced by "repo init --mirror", but
# unlike it, contains *all* projects for *all* versions of Android.
# If you already have mirror produced by repo, you can create symlink
# "android-mirror" pointing to it, then this script will download only
# projects missing in it (again, your mirror will be still usable for
# repo init --reference). To keep mirror up-to-date you, as expected,
# can use "repo sync" command.
#
set -xe

BASE="https://android.googlesource.com"
AOSP_MIRROR_DIR=android-mirror
# Uncomment to manually mirror specific projects
#PROJECTS="
#platform/external/astl
#"

if [ -z "$PROJECTS" ]; then
    if [ ! -f aosp-projects.txt ]; then
        wget "https://android.googlesource.com/?format=TEXT" -O aosp-projects.txt
    fi

    PROJECTS=$(grep -E "^(platform|device)" aosp-projects.txt)
fi

GIT_CLONE_OPTS=--mirror

TOP=$PWD
for p in $PROJECTS; do
    mkdir -p $TOP/$AOSP_MIRROR_DIR
    cd $TOP/$AOSP_MIRROR_DIR
    echo $p
    if [ -d $p.git ]; then
        continue
    fi
    parent=$(dirname $p)
    mkdir -p $parent
    cd $parent
    git clone $GIT_CLONE_OPTS $BASE/$p
    cd $TOP/$AOSP_MIRROR_DIR; cd $p.git
    git remote rename origin aosp
    git config remote.aosp.projectname $p
    git config remote.aosp.review https://android-review.googlesource.com/
    git config --unset remote.aosp.mirror
    # Default clone --mirror pattern is slighly more all-encompassing,
    # set to the same value as repo does.
    git config remote.aosp.fetch "+refs/heads/*:refs/heads/*"
done
